package com.study.test;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.GeneratePresignedUrlRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;

import java.io.File;
import java.net.URL;

/**
 * Hello world!
 */
public class App {

    static AmazonS3 s3;
    static String AWS_ACCESS_KEY = "1"; // 【你的 access_key】
    static String AWS_SECRET_KEY = ""; // 【你的 aws_secret_key】

    static String bucketName = "myna-application-on-prem"; // 【你 bucket 的名字】 # 首先需要保证 s3 上已经存在该存储桶

    static {
        s3 = new AmazonS3Client(new BasicAWSCredentials(AWS_ACCESS_KEY, AWS_SECRET_KEY));
        s3.setRegion(Region.getRegion(Regions.EU_WEST_1)); // 此处根据自己的 s3 地区位置改变
    }

    public static String uploadToS3(File tempFile, String remoteFileName) {
        try {
            String bucketPath = bucketName;
            s3.putObject(new PutObjectRequest(bucketPath, remoteFileName, tempFile)
                    .withCannedAcl(CannedAccessControlList.PublicRead));
            GeneratePresignedUrlRequest urlRequest = new GeneratePresignedUrlRequest(bucketName, remoteFileName);
            URL url = s3.generatePresignedUrl(urlRequest);
            return url.toString();
        } catch (AmazonServiceException ase) {
            ase.printStackTrace();
        } catch (AmazonClientException ace) {
            ace.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        File uploadFile = new File("D:/text.txt");
        String uploadKey = "test";
        uploadToS3(uploadFile, uploadKey);
    }


//        List<Integer> ids = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
//        Long count = ids.stream().filter(id -> id % 2 == 0).count();
//        System.out.printf("count : {%s}", count);
//
//        ids.forEach(new Consumer<Integer>() {
//            @Override
//            public void accept(Integer id) {
//                System.out.println(id);
//            }
//        });
//
//        ids.forEach(id -> System.out.println(id));
//
//        DecimalFormat decimalFormat = new DecimalFormat("000");
//        System.out.println(decimalFormat.format(1223));
}
